//
//  KABMallShopcartVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/20.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallShopcartVC.h"
#import "KABMallShopCartTCell.h"
#import "KABMallShoCarHeaderHFView.h"
#import "KABMallSureOrderVC.h"
#import "KABModel.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import <MJRefresh.h>
#import "KABMallBuyVC.h"
#import "UIColor+XDHex.h"
#import <UIScrollView+EmptyDataSet.h>

@interface KABMallShopcartVC ()<UITableViewDelegate, UITableViewDataSource, KABMallShopCartTCellDelegate, KABMallShoCarHeaderHFViewDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *allSelectBtn;
@property (weak, nonatomic) IBOutlet UILabel *allPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *allFreightLabel;
@property (weak, nonatomic) IBOutlet UIButton *allPayBtn;
@property (weak, nonatomic) IBOutlet UIView *bottomBgView;

@property (strong, nonatomic) UIBarButtonItem *editBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *completeBarBtnItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) KABMallShopCartModel *shopCartModel;

@property (assign, nonatomic) BOOL isEditing;

@end

static NSString *const kReuseCellId = @"KABMallShopCartTCell";
static NSString *const kHeaderViewId = @"KABMallShoCarHeaderHFView";

@implementation KABMallShopcartVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 请求数据
    if (![self.tableView.mj_header isRefreshing]) {
        [self requestShopCartListWithHeader:YES];
    }
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"购物车";
    
    self.editBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editBarBtnTapped:)];
    self.completeBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(completeBarBtnTapped:)];;
    self.navigationItem.rightBarButtonItem = self.editBarBtnItem;
}

- (void)initSubViews {
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.allSelectBtn addTarget:self action:@selector(allSelectBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.allPayBtn addTarget:self action:@selector(allPayBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.bottomBgView.hidden = YES;
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 50, 0);
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 141.0;
    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 48.0;
    //    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
    //    self.tableView.estimatedSectionFooterHeight = 44.0;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    // 请求数据(移到viewwillApprea里，每次进入购物车都要刷新一下购物车)
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"购物车竟然是空的" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.shopCartModel.sortList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = self.shopCartModel.sortList[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMallShopCartTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    NSArray *array = self.shopCartModel.sortList[indexPath.section];
    [cell configViewWithProDetail:array[indexPath.row] couldSel:YES isEdit:self.isEditing];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    KABMallShoCarHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
    NSArray *array = self.shopCartModel.sortList[section];
    BOOL wholeSel = [self.shopCartModel isWholeSelectedWithIndex:section];
    [view configViewWithProDetail:array.firstObject couldSel:YES wholeSel:wholeSel];
    view.section = section;
    view.delegate = self;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 6.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    NSArray *array = self.shopCartModel.sortList[indexPath.section];
    KABMallProDetail *detail = array[indexPath.row];
    detail.isSelected = !detail.isSelected;
    [self refreshWholeView];
}

#pragma mark - KABMallShopCartTCellDelegate
- (void)kABMallShopCartTCell:(KABMallShopCartTCell *)cell selBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSArray *array = self.shopCartModel.sortList[indexPath.section];
    KABMallProDetail *detail = array[indexPath.row];
    detail.isSelected = !detail.isSelected;
    [self refreshWholeView];
}

- (void)kABMallShopCartTCell:(KABMallShopCartTCell *)cell editBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSArray *array = self.shopCartModel.sortList[indexPath.section];
    KABMallProDetail *detail = array[indexPath.row];
    
    KABMallBuyVC *vc = [[KABMallBuyVC alloc] init];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.proDetail = detail;
    vc.completeBlock = ^() {
        [detail modelIdMergeToSkuId];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)kABMallShopCartTCell:(KABMallShopCartTCell *)cell decreaseBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSArray *array = self.shopCartModel.sortList[indexPath.section];
    KABMallProDetail *detail = array[indexPath.row];
    
    // 这里就需要校验库存是否足够
    if (detail.number > 1) {
        --detail.number;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"不能更少了喔"];
    }

//    [self refreshWholeView];
}
- (void)kABMallShopCartTCell:(KABMallShopCartTCell *)cell increaseBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSArray *array = self.shopCartModel.sortList[indexPath.section];
    KABMallProDetail *detail = array[indexPath.row];
    
    // 这里就需要校验库存是否足够
    if (detail.number < detail.selStock) {
        ++detail.number;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"库存不足"];
    }
    
//    [self refreshWholeView];
}

#pragma mark - KABMallShoCarHeaderHFViewDelegate
- (void)kABMallShoCarHeaderHFView:(KABMallShoCarHeaderHFView *)view section:(NSInteger)section selBtnTapped:(UIButton *)btn {
    BOOL wholeSel = [self.shopCartModel isWholeSelectedWithIndex:section];
    [self.shopCartModel setWholeSelected:!wholeSel withIndex:section];
    [self refreshWholeView];
}
//- (void)kABMallShoCarHeaderHFView:(KABMallShoCarHeaderHFView *)view section:(NSInteger)section delBtnTapped:(UIButton *)btn {
//    
//}

#pragma mark - event response
- (void)editBarBtnTapped:(UIBarButtonItem *)item {
    self.isEditing = YES;
}

- (void)completeBarBtnTapped:(UIBarButtonItem *)item {
    self.isEditing = NO;
    // 请求修改购物车
    [self requestEditShopCart];
}

- (void)allSelectBtnTapped:(UIButton *)btn {
    BOOL wholeSel = [self.shopCartModel isWholeSelected];
    [self.shopCartModel setWholeSelected:!wholeSel];
    [self refreshWholeView];
}
- (void)allPayBtnTapped:(UIButton *)btn {
    if (!self.shopCartModel.selProductCnt) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择商品"];
        return;
    }
    
    // 这里要判断是删除还是结算
    if (self.isEditing) {
        // 删除
        [self sureToDeleteSelectProduct];
        return;
    }
    
    KABMallSureOrderVC *vc = [[KABMallSureOrderVC alloc] init];
    vc.shoppingcartIdArray = [self.shopCartModel selectShoppingcartIdArray];
    vc.productArray = [self.shopCartModel selectProductArray];
    [self showViewController:vc sender:nil];
}

#pragma mark - private methods
- (void)sureToDeleteSelectProduct {
    NSString *title = [NSString stringWithFormat:@"确认将这%zd个宝贝删除？", self.shopCartModel.selectProductArray.count];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestDeleteShopCart];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.navigationItem.rightBarButtonItem = self.isEditing ? self.completeBarBtnItem : self.editBarBtnItem;
    
    self.allSelectBtn.selected = [self.shopCartModel isWholeSelected];
    NSString *titleStr = @"合计：";
    NSString *priceStr = [NSString stringWithFormat:@"%@￥%.2f", titleStr, self.shopCartModel.wholeSelOriginalPrice / 100.0];
    NSMutableAttributedString *mAStr = [[NSMutableAttributedString alloc] initWithString:priceStr];
    NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:KABGlobalColorTabBarItemColor],
                          NSFontAttributeName : [UIFont systemFontOfSize:18.0]};
    [mAStr addAttributes:dic range:NSMakeRange(titleStr.length, priceStr.length - titleStr.length)];
    self.allPriceLabel.attributedText = mAStr;
    self.allPriceLabel.hidden = self.isEditing;
    self.allFreightLabel.hidden = self.isEditing;
    
    NSString *btnTitle = self.isEditing ? @"删除" : @"结算";
    [self.allPayBtn setTitle:btnTitle forState:UIControlStateNormal];
    
    self.bottomBgView.hidden = !self.shopCartModel.total_rows;
    
    [self.tableView.mj_header setHidden:self.isEditing];
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestShopCartListWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestShopCartListWithHeader:(BOOL)isHeader {
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiShoppingcart] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求商品列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.shopCartModel = [KABMallShopCartModel yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self.shopCartModel sortWithSameShop];
            [self.shopCartModel transSkuIdToModelId];
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求商品列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestEditShopCart {
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"product_detail" : [self.shopCartModel.product_list yy_modelToJSONObject]};
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiShoppingcart] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求修改购物车返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
            // 这里要还原数据，类似于重新请求
            [self requestShopCartListWithHeader:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求修改购物车失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestDeleteShopCart {
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSString *selStr = [[self.shopCartModel selectShoppingcartIdArray] yy_modelToJSONString];
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"shoppingcart_id_list" : selStr};
    [[XDAFNetworking sharedInstance] DELETE:[ApiManager apiShoppingcart] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求删除购物车返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self.shopCartModel deleteSelectProduct];
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求删除购物车失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (void)setIsEditing:(BOOL)isEditing {
    _isEditing = isEditing;
    
    [self refreshWholeView];
}

@end
